<template>
  <div class="preview">
    <!-- <div class="event"></div> -->
    <div class="jqzoom">
      <div class="event" @mousemove="handler"></div>
      <img :src="imgObj.imgUrl" />
      <div class="mask" ref="mask"></div>
    </div>

    <div class="maxbox">
      <img :src="imgObj.imgUrl" ref="big" />
    </div>
  </div>
</template>
<script>
export default {
  name: 'Zoom',
  props: ['skuImageList'],
  data() {
    return {
      currentIndex: 0,
    }
  },
  computed: {
    imgObj() {
      return this.skuImageList[this.currentIndex] || {}
    },
  },
  mounted() {
    // 全局事件总线，获取兄弟组件传递过来的索引值
    this.$bus.$on('getIndex', (index) => {
      // console.log(index)
      // 修改当前响应式数据
      this.currentIndex = index
    })
  },
  methods: {
    handler(event) {
      this.isShow = true
      let mask = this.$refs.mask
      let big = this.$refs.big
      let left = event.offsetX - mask.offsetWidth / 2
      let top = event.offsetY - mask.offsetHeight / 2
      // 约束
      if (left <= 0) {
        left = 0
      }
      if (left >= mask.offsetWidth) {
        left = mask.offsetWidth
      }
      if (top <= 0) {
        top = 0
      }
      if (top >= mask.offsetHeight) {
        top = mask.offsetHeight
      }
      // 修改元素的left与top
      mask.style.left = left + 'px'
      mask.style.top = top + 'px'
      big.style.left = -2 * left + 'px'
      big.style.top = -2 * top + 'px'
    },
  },
}
</script>
<style scoped>
.outer .con .mainCon .previewWrap .preview {
  width: 400px;
  height: 400px;
  border: 1px solid #dfdfdf;
}
.outer .con .mainCon .previewWrap .preview .jqzoom {
  cursor: pointer;
  width: 400px;
  height: 400px;
  position: relative;
}
.outer .con .mainCon .previewWrap .preview .jqzoom img {
  width: 100%;
}

.outer .con .mainCon .previewWrap .preview .jqzoom .mask {
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
  left: 0;
  top: 0;
  border: 1px solid #ddd;
  display: none;
}
.outer .con .mainCon .previewWrap .preview .jqzoom:hover .mask {
  display: block;
}
.outer .con .mainCon .previewWrap .preview:hover .maxbox {
  display: block;
}
.outer .con .mainCon .previewWrap .preview .maxbox {
  width: 400px;
  height: 400px;
  position: absolute;
  left: 420px;
  top: 0px;
  overflow: hidden;
  z-index: 20;
  border: 1px solid #ddd;
  display: none;
}
.outer .con .mainCon .previewWrap .preview .maxbox img {
  width: 800px;
  height: 800px;
  display: block;
  position: absolute;
}
.event {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 0;
}
</style>
